import pygame, sys
import random
#===================================================================================================#
pygame.init()
screen = pygame.display.set_mode((576, 960))
clock = pygame.time.Clock()
#===================================================================================================#
bg_surface = pygame.image.load("assets/background-day.png").convert()
bg_surface = pygame.transform.scale2x(bg_surface)

floor_surface = pygame.image.load("assets/base.png")
floor_surface = pygame.transform.scale2x(floor_surface)

bird_surface = pygame.image.load("assets/bluebird-midflap.png").convert()
bird_surface = pygame.transform.scale2x(bird_surface)
bird_rect = bird_surface.get_rect(center = (100, 400))

pipe_surface = pygame.image.load("assets/pipe-green.png").convert()
pipe_surface = pygame.transform.scale2x(pipe_surface)

pipe_list = []
pipe_height = [400, 600, 700]
#===================================================================================================#
floor_x_pos = 0
bg_x_pos = 0

gravity = 0.25
fall = 0

SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE, 1200)

def draw_floors():
    screen.blit(floor_surface, (floor_x_pos, 800))
    screen.blit(floor_surface, (floor_x_pos + 576, 800))

def draw_backgrounds():
    screen.blit(bg_surface, (bg_x_pos, 0))
    screen.blit(bg_surface, (bg_x_pos + 576, 800))

def create_pipes():
    random_pipe_y = random.choice(pipe_height)
    top_pipe = pipe_surface.get_rect(midbottom = (800, random_pipe_y - 300))
    bottom_pipe = pipe_surface.get_rect(midtop = (800, random_pipe_y))

    return top_pipe, bottom_pipe

def move_pipes(pipes):
    for pipe in pipes:
        pipe.centerx -= 5
    
    return pipes

def draw_pipes(pipes):
    for pipe in pipes:
        screen.blit(pipe_surface, pipe)
#===================================================================================================#
while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            fall = 0
            fall -= 10

        if event.type == SPAWNPIPE:
            pipe_list.extend(create_pipes())

    bg_x_pos -= 0.6
    draw_backgrounds()
    if bg_x_pos <= -576:
        bg_x_pos = 0

    fall += gravity
    bird_rect.centery += fall
    screen.blit(bird_surface, bird_rect)


    pipe_list = move_pipes(pipe_list)
    # draw_pipes(pipe_list)

    
    floor_x_pos -= 2
    draw_floors()
    if floor_x_pos <= -576:
        floor_x_pos = 0


    pygame.display.update()
    clock.tick(120)